package com.example.food_contract_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.food_contract_system.domain.Rotation;
import com.example.food_contract_system.service.RotationService;
import com.example.food_contract_system.mapper.RotationMapper;
import com.example.food_contract_system.util.R;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
* @author Lhy
* @description 针对表【rotation】的数据库操作Service实现
* @createDate 2023-07-14 13:01:56
*/
@Service
public class RotationServiceImpl extends ServiceImpl<RotationMapper, Rotation> implements RotationService{

    @Autowired
    private RotationMapper rotationMapper;

    @Override
    public R insertRotation(String href) {

        JSONObject jsonObj = new JSONObject(href);
        String msgValue = jsonObj.getString("href");

        UUID uuid = UUID.randomUUID();
        String s = uuid.toString();

        Rotation rotation = new Rotation();
        rotation.setPId(s.substring(0,4));
        rotation.setPSrc("http://localhost:8081/index/"+msgValue);

        rotationMapper.insert(rotation);
        return R.ok();
    }

    @Override
    public R getRotation() {
        List<Rotation> rotations = rotationMapper.selectList(null);
        if (rotations.size() > 0){
            return R.ok().put("data",rotations);
        }
        return R.error();
    }

    @Transactional
    @Override
    public R showPicture(String pId, String pStatus) {
        //1.首先判断是展示还是取消展示
        if (pStatus.equals("0")){
            // 取消展示
            rotationMapper.updateStatus("1",pId);
            return R.ok().put("msg","取消成功!");
        }else{
            // 展示
            // 判断是否已经六张图片
            List<Rotation> rotationList = rotationMapper.selectList(new QueryWrapper<Rotation>()
                    .eq("p_status", "0"));
            if (rotationList.size() == 6){
                return R.error(500,"只能展示六张图片");
            }
            // 低于六张，可以对图片进行展示处理
            rotationMapper.updateStatus("0",pId);

            return R.ok().put("msg","添加成功!");
        }

    }

    @Transactional
    @Override
    public R deletePicture(String pId) {
        rotationMapper.deleteMyself(pId);
        return R.ok().put("msg","删除成功!");
    }

    @Override
    public R getRotationList() {
        List<Rotation> p_status = rotationMapper.selectList(new QueryWrapper<Rotation>()
                .eq("p_status", "0"));
        return R.ok().put("data",p_status);
    }
}




